﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using TicTacToe.UI;
using TicTacToe.Core.Statistics;

namespace TicTacToe
{
    partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Debug.Print("3DTicTacToe starting");

            Task.Factory.StartNew(() => DatabaseManager.Initialize())
                .ContinueWith(task =>
                {
                    if (!task.IsFaulted)
                        return;

                    Action action = () =>
                    {
                        DatabaseManager.EnableDataCollection = false;
                        MessageBox.Show("Error loading statistics database" +
                            Environment.NewLine + Environment.NewLine + task.Exception.InnerException.Message,
                            "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    };
                    Dispatcher.Invoke(action);
                });

            new StartWindow().Show();
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            DatabaseManager.Instance.Save();
        }
    }
}
